package cz.muni.fi.pa165.sme.client.panels.sportActivity;

import cz.muni.fi.pa165.sme.client.fo.SportActivityFO;
import cz.muni.fi.pa165.sme.client.pages.sportActivity.ActivityListPage;
import cz.muni.fi.pa165.sme.ws.EndpointManager;
import cz.muni.fi.pa165.sportmanager.sportactivityws.CreateSportActivityRequest;
import cz.muni.fi.pa165.sportmanager.sportactivityws.SportActivity;
import cz.muni.fi.pa165.sportmanager.sportactivityws.SportActivityWS;
import cz.muni.fi.pa165.sportmanager.sportactivityws.UpdateSportActivityRequest;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.NumberTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.core.convert.ConversionService;

/**
 * @author jirankova
 */
public class ActivityForm extends Panel {

	@SpringBean
	private EndpointManager endpointManager;

	@SpringBean(name = "conversionServiceClient")
	private ConversionService conversionService;

	public ActivityForm(final String id, final IModel<SportActivityFO> model) {
		super(id, model);
		
		final SportActivityWS sportActivityService = endpointManager.getSportActivityWS();

		//title, speed
		final FormComponent<String> title = new TextField<String>("title");
		title.setRequired(true);

		final FormComponent<Long> speed = new NumberTextField<Long>("speed");

		final Form<SportActivityFO> activityForm = new Form<SportActivityFO>("activityForm", model) {
			@Override
			protected void onSubmit() {
				super.onSubmit();
				final SportActivityFO sportActivityFO = model.getObject();
				final SportActivity activity = conversionService.convert(sportActivityFO, SportActivity.class);

				if(activity.getId() != null) {
					final UpdateSportActivityRequest updateSportActivityRequest = new UpdateSportActivityRequest();
					updateSportActivityRequest.setSportActivities(activity);
					sportActivityService.updateSportActivity(updateSportActivityRequest);
				} else {
					final CreateSportActivityRequest createSportActivityRequest = new CreateSportActivityRequest();
					createSportActivityRequest.setSportActivities(activity);
					sportActivityService.createSportActivity(createSportActivityRequest);
				}

				setResponsePage(ActivityListPage.class);
			}
		};

		activityForm.add(title);
		activityForm.add(speed);

		add(activityForm);

		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
		feedbackPanel.setOutputMarkupId(true);
		add(feedbackPanel);
	}
}
